<template>
  <page-wrapper>
    <n-card :bordered="false" class="mb-3 proCard">
      <n-space align="center">
        <n-input-group style="width: 380px">
          <n-input
            :style="{ width: '100%' }"
            v-model:value="params.region_name"
            clearable
            placeholder="请输入区域名称"
            @keyup.enter="reloadTable"
          />
          <n-button type="primary" @click="reloadTable">
            <template #icon>
              <n-icon>
                <SearchOutlined />
              </n-icon>
            </template>
            查询
          </n-button>
        </n-input-group>
      </n-space>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :cascade="false"
        :pagination="false"
        allow-checking-not-loaded
        :actionColumn="actionColumn"
        @load="onLoad"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="openCreateDrawer">
            <template #icon>
              <n-icon>
                <FileAddOutlined />
              </n-icon>
            </template>
            添加区域
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :regionList="regionTreeData"
      @change="reloadTable"
    />
  </page-wrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicColumn, BasicTable, TableAction } from '@/components/Table';
  import { FileAddOutlined, SearchOutlined } from '@vicons/antd';
  import { columns } from './columns';
  import { provinceList, parentList, regionTreeList, deleteRegion } from '@/api/system/region';
  import CreateDrawer from './CreateDrawer.vue';

  const message = useMessage();
  const tableRef = ref();
  const createDrawerRef = ref();
  const drawerTitle = ref('添加区域');
  const regionTreeData = ref([]);

  const params = reactive({
    role_name: '',
  });

  const actionColumn: BasicColumn = reactive({
    width: 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            onPositiveClick: handleDelete.bind(null, record),
            isConfirm: true,
            confirmContent: '您确定要删除吗？',
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    const tableData = await provinceList(_params);
    tableData.forEach((item) => {
      item.isLeaf = false;
    });
    return {
      list: tableData,
    };
  };

  async function onLoad(row: Record<string, unknown>) {
    return new Promise<void>(async (resolve) => {
      const list = await parentList({ parentId: row.id });
      list.forEach((item) => {
        item.isLeaf = item.is_district;
      });
      row.children = list;
      resolve();
    });
  }

  function openCreateDrawer() {
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    tableRef.value.reload();
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    drawerTitle.value = '编辑区域';
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.id);
  }

  function handleDelete(record: Recordable) {
    deleteRegion({ id: record.id }).then(() => {
      message.success('删除成功');
      reloadTable();
    });
  }

  onMounted(async () => {
    const list = await regionTreeList();
    regionTreeData.value = list;
  });
</script>

<style lang="less" scoped></style>
